package com.exchangeek.server.service.RESTful;

import com.exchangeek.server.entity.bean.User;
import com.exchangeek.server.service.definition.UserInfoServiceDefinition;
import com.exchangeek.server.service.mysql.UserInfoDatabaseService;
import com.sun.jersey.spi.resource.Singleton;

import javax.annotation.PostConstruct;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;

/**
 * Created with IntelliJ IDEA.
 * Project Name: Exchangeek_Server
 * Date Created: 2013/09/12 下午2:03
 *
 * @author Wings
 */

@Singleton
@Path("/user")
public class UserInfoService implements UserInfoServiceDefinition {

    private UserInfoDatabaseService databaseService;

    @PostConstruct
    private void init() {
        final String databaseName = "exchangeek";
        databaseService = new UserInfoDatabaseService(databaseName);
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Override
    public Response createUser(User user) {
        String result = (String) databaseService.createUser(user);
        if (result == null || "".equals(result)) {
            return Response.status(400).build();
        }
        return Response.created(URI.create(result)).build();
    }

    @GET
    @Path("{id}/{hash}")
    @Produces(MediaType.APPLICATION_JSON)
    @Override
    public User queryUser(@PathParam("id") String userName, @PathParam("hash") String hash) {
        return databaseService.queryUser(userName, hash);
    }

    @PUT
    @Path("{id}/{hash}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Override
    public Response updateUser(@PathParam("id") String oldUserName, @PathParam("hash") String oldHash, User user) {
        String result = (String) databaseService.updateUser(oldUserName, oldHash, user);
        if (result == null || "".equals(result)) {
            return Response.status(400).build();
        }
        return Response.ok().build();
    }

    @DELETE
    @Path("{id}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Override
    public Response deleteUser(@PathParam("id") String userName) {
        String result = (String) databaseService.deleteUser(userName);
        if (result == null || "".equals(result)) {
            return Response.status(403).build();
        }
        return Response.ok().build();
    }
}
